package com.github.framework.webmvc.servlet;

import java.io.File;

/**
 * @program: springv2
 * @description: 将页面变成一个View对象，可能涉及参数的渲染
 * @author: Pop
 * @create: 2021-06-26 22:56
 **/
public class ViewResolver {
    //只能解析以html结尾的文件
    private final String DEFAULT_TEMPLATE_SUFFIX = ".html";
    private File templateRootDir;

    public ViewResolver(String templateRoot)
    {
        String templateRootPath = this.getClass().getClassLoader().getResource(templateRoot).getFile();
        templateRootDir = new File(templateRootPath);
    }

    public View resolveViewName(String viewName)
    {
        if(null == viewName || "".equals(viewName)){return null;}
        viewName = viewName.endsWith(DEFAULT_TEMPLATE_SUFFIX)?viewName:(viewName+DEFAULT_TEMPLATE_SUFFIX);
        // 将多余的斜杠去掉
        File templateFile = new File((templateRootDir.getPath()+"/"+viewName).replaceAll("/+","/"));
        return new View(templateFile);
    }
}
